package com.css.fxfzxczh.zcpt.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzxczh.constants.FxfzConstants;
import com.css.fxfzxczh.util.BuildUrl;
import com.css.fxfzxczh.util.CreateGson;
import com.css.fxfzxczh.util.RestTemplateUtil;
import com.css.fxfzxczh.zcpt.sys.entity.RoleEntity;
import com.css.fxfzxczh.zcpt.sys.entity.UserRegister;
import com.css.fxfzxczh.zcpt.sys.service.SysAreaService;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.*;

@Service
public class SysAreaServiceImpl implements SysAreaService {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String jsonSAreaTree(String areaId) {
        //读取配置文件
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String sysId = configGroup.getProperty("app.system.id");
        String url = configGroup.getProperty("baseRestUrl") + "/sorg_dzj/getDivisionTree?id=" + areaId;
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("id", areaId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return responseEntity.getBody();
    }

    @Override
    public String getChildAreaById(String divisionId) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String sysId = configGroup.getProperty("app.system.id");
        String url = configGroup.getProperty("baseRestUrl") + "/sorg_dzj/getChildDivisionById?id=" + divisionId;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("id", divisionId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return responseEntity.getBody();
    }

    @Override
    public List getAllDivisionCode() {
        Gson gson = CreateGson.createGson();
        String jsonStr = redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaCodeList");
        List sysAreaList = gson.fromJson(jsonStr, List.class);
        if (sysAreaList == null || sysAreaList.size() == 0) {
            String url = BuildUrl.buildUrl() + "/sorg_dzj/getAllDivisionCode";
            Map<String, Object> paramMap = new HashMap<>(1);
            ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
            sysAreaList = CreateGson.createGson().fromJson(responseEntity.getBody(), List.class);
            redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY + "areaCodeList", CreateGson.createGson().toJson(sysAreaList));
            return sysAreaList;
        }
        return sysAreaList;
    }

    @Override
    public List getAllDivision() {
        Gson gson = CreateGson.createGson();
        String jsonStr = redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaList");
        List sysAreaList = gson.fromJson(jsonStr, List.class);
        List<String> codeList = new ArrayList<>();
        if (sysAreaList == null || sysAreaList.size() == 0) {
            String url = BuildUrl.buildUrl() + "/sorg_dzj/getAllDivision";
            Map<String, Object> paramMap = new HashMap<>(1);
            ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
            sysAreaList = CreateGson.createGson().fromJson(responseEntity.getBody(), List.class);
            Map<String, String> tempMap = new HashMap<>();
            Map<String, String> areaIdCodeMap = new HashMap<>();
            if (sysAreaList != null && sysAreaList.size() > 0) {
                for (int i = 0; i < sysAreaList.size(); i++) {
                    LinkedTreeMap map = (LinkedTreeMap) sysAreaList.get(i);
                    Map<String, String> linkMap = new HashMap<>();
                    tempMap.put(map.get("uuid").toString(), map.get("name").toString());
                    areaIdCodeMap.put(map.get("uuid").toString(), map.get("code").toString());
                    codeList.add(map.get("code").toString());
                }
            }
            if (codeList.size() > 0) {
                redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY + "areaCodeList", CreateGson.createGson().toJson(codeList));
            }
            if (tempMap.size() > 0) {
                redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY + "areaMap", CreateGson.createGson().toJson(tempMap));
            }
            if (areaIdCodeMap.size() > 0) {
                redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap", CreateGson.createGson().toJson(areaIdCodeMap));
            }
            assert sysAreaList != null;
            if (sysAreaList.size() > 0) {
                redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY + "areaList", CreateGson.createGson().toJson(sysAreaList));
            }
            return sysAreaList;
        }
        return sysAreaList;
    }

    @Override
    public String getDivisionCodeById(String divisionId) {
        String url = BuildUrl.buildUrl() + "/sorg_dzj/getDivisionCodeById?divisionId=" + divisionId;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("divisionId", divisionId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return responseEntity.getBody();
    }

    @Override
    public String getIdByCondition(String province, String city, String area) {
        city = StringUtils.isBlank(city) ? "-1" : city;
        area = StringUtils.isBlank(area) ? "-1" : area;
        String url = BuildUrl.buildUrl() + "/sorg_dzj/getIdByCondition?province=" + province + "&city=" + city + "&area=" + area;
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("province", province);
        paramMap.put("city", city);
        paramMap.put("area", area);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return responseEntity.getBody();
    }

    @Override
    public String getAreaCodeByUserId(String userId) {
        String url = BuildUrl.buildUrl() + "/suser_dzj/getAreaCodeByUserId?userId=" + userId;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("userId", userId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return responseEntity.getBody();
    }

    @Override
    public String getAreaNameByAreaId(String areaId) {
        String url = BuildUrl.buildUrl() + "/sorg_dzj/getAreaNameByAreaId?areaId="+areaId;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("areaId",areaId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return (String) JSONObject.parse(responseEntity.getBody());
    }


    /**
     * 直辖市查询模型失败
     */
    @Override
    public String getParentId(String areaId) {
        String url = BuildUrl.buildUrl() + "/sorg_dzj/getParentId?areaId=" + areaId;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("areaId", areaId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        return (String) JSONObject.parse(responseEntity.getBody());
    }

    /**
     * 将未注册的手机号注册,并将该人员挂到省地震局下
     */
    @Override
    public String registerNewUser(UserRegister sUser) {
        //读取配置文件
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("baseRestUrl") + "/suser_dzj/registerNewUser";
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("password", sUser.getPassword());
        paramMap.put("mobile", sUser.getMobile());
        try {
            paramMap.put("realName", URLEncoder.encode(sUser.getRealName(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        paramMap.put("provinceId", sUser.getProvinceId());
        paramMap.put("cityId", sUser.getCityId());
        paramMap.put("countyId", sUser.getCountyId());
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendPostHttpRequest(url, paramMap);
        String body = stringResponseEntity.getBody();
        String areaCode = (String) JSONObject.parse(body);
        return areaCode;
    }

    @Override
    public List<Map> getRole() {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String sysId = configGroup.getProperty("app.system.id");
        String url = BuildUrl.buildUrl() + "/srole_dzj/getSRoleBySysId?sysId="+sysId;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("sysId",sysId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        String role = responseEntity.getBody();
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        return roleMaps;
    }

    @Override
    public String getSRoleUser(String roleId,String userId) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String sysId = configGroup.getProperty("app.system.id");
        String url = BuildUrl.buildUrl() + "/srole_dzj/addSRoleUser?roleId="+roleId+"&userId="+userId+"&sysId="+sysId;
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("roleId",roleId);
        paramMap.put("userId",userId);
        paramMap.put("sysId",sysId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
        String body = responseEntity.getBody();
        return body;
    }
    //roleIds多个以逗号分隔
    @Override
    public void deleteRole(String roleIds,String userId) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String sysId = configGroup.getProperty("app.system.id");
        String url = BuildUrl.buildUrl() + "/srole_dzj/delSUserRole?roleId="+roleIds+"&userId="+userId+"&sysId="+sysId;
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("roleId",roleIds);
        paramMap.put("userId",userId);
        paramMap.put("sysId",sysId);
        ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
    }
}
